package com.haojiang.mh.remote.ui.dialog

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.haojiang.mh.AppContext
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.BleGroupDialogFragAdapter
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.bean.BleRssiDevice
import com.haojiang.mh.remote.bean.DeviceModifySuccessEvent
import com.haojiang.mh.remote.callback.IBleItemClickLisenter
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.BleEvent
import com.haojiang.mh.remote.event.BleStatus
import com.haojiang.mh.remote.event.ConnectEvent
import com.haojiang.mh.remote.event.SurfaceEvent
import com.haojiang.mh.remote.utils.BleUtil
import com.haojiang.mh.remote.utils.BleUtil.Companion.ble
import com.haojiang.mh.remote.utils.BleUtil.Companion.bleRssiDeviceList
import com.haojiang.mh.remote.utils.BleUtil.Companion.devConnects
import com.haojiang.mh.remote.utils.BleUtil.Companion.devDisconnectAll
import com.haojiang.mh.remote.utils.BleUtil.Companion.devScan
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.Util.Companion.checkBleStatus
import kotlinx.android.synthetic.main.frag_dialog_ble_group.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class BleGroupDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {
        private var GROUP_TYPE = "group_type"
        private var GROUP_ID = "group_id"

        val instance by lazy {
            BleGroupDialogFrag()
        }


        fun show(
            fragmentActivity: FragmentActivity,
            groupType: Int = EConnect.CONNECT_GROUP_SINGLE.data,
            groupId: Long = 0L
        ) {
            val fm = fragmentActivity.supportFragmentManager
            fm.executePendingTransactions()
            fm.beginTransaction().remove(instance)
            instance.arguments = Bundle(bundleOf(GROUP_TYPE to groupType, GROUP_ID to groupId))
            instance.show(
                fragmentActivity.supportFragmentManager,
                BleGroupDialogFrag::class.java.simpleName
            )
        }
    }

    private val bleGroupDialogFragAdapter by lazy {
        BleGroupDialogFragAdapter(
            activity!!,
            bleRssiDeviceList
        )
    }

    //    private val bleGroupDialogFragAdapter = BleGroupDialogFragAdapter(activity!!, bleRssiDeviceList)
    private var groupType = EConnect.CONNECT_GROUP_SINGLE.data
    private var groupId = 0L

    /**
     * 点击后回调并连接ble设备
     */
    private var iOnBleItemClickLisenter = object : IBleItemClickLisenter {
        override fun onClick(bleDeviceList: ArrayList<BleRssiDevice>, connectType: Int) {
            context?.let {
                if (!checkBleStatus(it)) return
//                activity?.let { it -> devConnect(it, bleDevice) }
//                ble.stopScan()  //停止扫描
                //单机连接  初始化最后一次连接信息
                if (connectType == EConnect.CONNECT_GROUP_TEST.data) {
                    devConnects(bleDeviceList)
                }
//                lastBleDeviceList.clear()
//                lastBleDeviceList.addAll(bleDeviceList)
//                lastGroupType = GROUP_TYPE_NONE
//                lastGroupId = 0L
//                SelectDialogFrag.show(activity!!, GROUP_TYPE_NONE, 0L)
//                val interfaceNo = readInterfaceNo()
//                if (TextUtils.isEmpty(interfaceNo)) {
//                    SelectDialogFrag.show(activity!!)
//                } else {
//                    val funList = SurfaceUtil.map.get(interfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//                    if (funList != null) {
//                        if (funList.size > 0) {
//                            dismiss()
//                            devConnects(context!!, lastBleDeviceList)
//                            EventBus.getDefault().post(FunctionEvent(funList!!))
//                        }
//                    }
//                }
            }
        }
    }


    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog_fullscreen)
        groupType = arguments!!.getInt(GROUP_TYPE)
        groupId = arguments!!.getLong(GROUP_ID)
    }


    override fun onSubCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        return inflater.inflate(R.layout.frag_dialog_ble_group, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true)                                                                                                //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(true)                                                                        //dialog外面是否可以点击

        val params = dialog!!.window!!.attributes
        val context = context
        context?.let {
            params.width = LinearLayout.LayoutParams.MATCH_PARENT
            params.height = LinearLayout.LayoutParams.MATCH_PARENT
            params.gravity = Gravity.CENTER
            //高度自己定义
            dialog!!.window!!.setLayout(params.width, params.height)
        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {
        bleGroupDialogFragAdapter.iOnBleItemClickLisenter = iOnBleItemClickLisenter
//        bleDialogFragAdapter.groupType = groupType
//        bleDialogFragAdapter.viewList.clear()
        rvGroup.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        rvGroup.layoutManager = LinearLayoutManager(context)
        rvGroup.itemAnimator = null
        rvGroup.adapter = bleGroupDialogFragAdapter

        when (groupType) {
//        when (lastGroupType) {
            EConnect.CONNECT_GROUP_SINGLE.data -> {
                ivGroupType.visibility = View.VISIBLE
                ivGroupType.setImageResource(R.drawable.ic_group_single_n)
            }
            EConnect.CONNECT_GROUP_MULTIPLE.data -> {
                ivGroupType.visibility = View.VISIBLE
                ivGroupType.setImageResource(R.drawable.ic_group_multiple_n)
            }
            EConnect.CONNECT_GROUP_SPLIT.data -> {
                ivGroupType.visibility = View.VISIBLE
                ivGroupType.setImageResource(R.drawable.ic_group_split_n)
            }
        }

        //初始化刷新控件
        swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.GREEN)
        //刷新监听
        swipeRefreshLayout.setOnRefreshListener {
            activity?.let {
                if (!checkBleStatus(activity!!)) {
                    swipeRefreshLayout.isRefreshing = false
                } else {
//                    devDisconnectAll()
                    if (ble.isBleEnable) {
                        devScan()
//                        ThreadUtils.submit {
//                        }
                    } else {
                        swipeRefreshLayout.isRefreshing = false
                    }
                }
            }
        }

        //返回按键
        ivBack.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                dismiss()
//                devDisconnectAll()
            }
        })


        tvSave.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                val groupValueList = bleGroupDialogFragAdapter.getSelectList()
                if (groupValueList.size > 0) {
                    if (BleUtil.addGroupValueList(context!!, groupId, groupValueList)) {
                        dismiss()
                        val bleDeviceList = ArrayList<BleRssiDevice>()
                        groupValueList.forEach {
                            bleDeviceList.add(it.bleRssiDevice)
                        }
                        EventBus.getDefault().post(
                            ConnectEvent(
                                EStep.STEP_SELECT_DEVICE.data,
                                lastConnect.connectType,
                                groupId,
                                bleDeviceList
                            )
                        )
                    }
                } else {
                    showToast(
                        AppContext.instance().getString(R.string.m_selection_can_not_be_empty)
                    )
                }
            }
        })

        dialog!!.setOnKeyListener(object : DialogInterface.OnKeyListener {
            override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
//                    LogUtil.e("马达测试退出")
                    devDisconnectAll()
//                    return true
                }
                return false
            }
        })

        devDisconnectAll()
        devScan()
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun onDeviceModifyEvent(event: DeviceModifyEvent) {
//        if (event.className.equals(GroupFrag::class.java.simpleName)) {
//            ModifyDialogFrag.show(activity!!, event.className, event.bleRssiDevice.bleAddress, event.bleRssiDevice.bleName, event.bleRssiDevice.deviceAlias!!)
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDeviceModifySuccessEvent(event: DeviceModifySuccessEvent) {
//        if (event.className.equals(GroupFrag::class.java.simpleName)) {
        bleGroupDialogFragAdapter.modifyItem(event.bleAddress, event.deviceAlias)
//        }
    }

    //选择界面确定界面后隐藏当前界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFunctionEvent(event: SurfaceEvent) {
        dismiss()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBleEvent(event: BleEvent) {
        when (event.devStatus) {
            BleStatus.SCAN_PREPARE -> {
                bleRssiDeviceList.clear()
//                bleDialogFragAdapter.initData(groupType)
                bleGroupDialogFragAdapter.initData(groupType)        //初始化蓝牙列表dapter
                if (!swipeRefreshLayout.isRefreshing) {
                    swipeRefreshLayout.isRefreshing = true
                }
            }

            BleStatus.SCAN_RSSI_CHANGED -> {
                val data = event.data
                if (data != null) {
                    bleGroupDialogFragAdapter.notifyItemChanged(data.toInt())
//                    bleGroupDialogFragAdapter.dataRefresh()
//                    bleGroupDialogFragAdapter.notifyDataSetChanged()
                }
            }

            BleStatus.SCAN_FOUND -> {
                bleGroupDialogFragAdapter.notifyDataSetChanged()
            }

            BleStatus.SCAN_STOP -> {
//                bleGroupDialogFragAdapter.dataRefresh()
                swipeRefreshLayout?.let {
                    if (swipeRefreshLayout.isRefreshing) {
                        swipeRefreshLayout.isRefreshing = false
                    }
                }
            }

            BleStatus.GATT_SERVICE_CONNECT -> {
//                val bleDevice = event.bleDevice
//                if (bleDevice != null) {
//                    if (!MotorTestDialogFrag.instance.isAdded) {
//                        MotorTestDialogFrag.show(activity!!)
//                    }
//                }
            }
        }
    }


//    private fun getFunction(bleName: String) {
//        val funList = SurfaceUtil.map.get(bleName.substring(0, 4).toUpperCase())
//        //如果界面的功能列表不存在
//        if (funList == null) {
//            showToast(getString(R.string.m_interface_not_exist))    //提示界面不存在断开连接
////            BleUtil.devDisconnect()
//        } else {
////            LogUtil.e("是不是加載了三次" + funList.size)
//            //如果是外置蓝牙直接广播获取的界面功能列表
//            EventBus.getDefault().post(FunctionEvent(funList))
//        }
//        dialog?.hide()
//    }

    override fun initDestroy() {
        ble.stopScan()
        EventBus.getDefault().unregister(this)
    }

}